import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import { CallerSourceType, CanvasMethod } from '../main/store/canvas/canvasType'
import CanvasData from '../main/store/canvas/canvas'

// Custom APIs for renderer
export const api = {
  //处理画布数据
  handleCanvasData: <M extends CanvasMethod>(
    methodName: M,
    callerSource: CallerSourceType, // 新增调用来源
    isBroadcast: boolean, // 是否广播
    args: Parameters<(typeof CanvasData)[M]>
  ): ReturnType<(typeof CanvasData)[M]> => {
    return ipcRenderer.sendSync('handleCanvasData', methodName, callerSource, isBroadcast, args)
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
